<template>
  <div class="app-container">
    <div id="topSearch" class="topSearch">
      <el-row>
        <el-button type="primary" @click="showDialog('add')">Add</el-button>
        <div class="right">
          <el-input
            v-model="searchCriteria.name"
            maxlength="50"
            clearable
            placeholder="name"
          />
          <el-button type="primary" @click="searchData()">Search</el-button>
        </div>
      </el-row>
    </div>

    <el-table
      ref="specTable"
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      :tree-props="{ children: 'listLeaf', hasChildren: 'hasChildren' }"
      @row-click="toggleRow"
    >
      <el-table-column prop="name" label="Name" />
      <el-table-column prop="storeName" label="Store" />
      <el-table-column label="Store Type">
        <template slot-scope="scope">
          {{ storeMap[scope.row.storeType] }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="Operation" width="130">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="showDialog('edit', scope.row)"
          >Edit</el-button>
          <el-button
            type="text"
            @click="deleteItem(scope.row)"
          >Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="tableData.length"
      id="btmPagination"
      :class="{ open: sidebar }"
      :current-page="currentPage"
      :page-sizes="[10, 30, 50, 100, 200]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑商品规格 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="400px"
      @close="closeDialog('ruleForm')"
    >
      <div v-loading="dialogLoading" class="dialogLoadingBox">
        <el-form
          ref="ruleForm"
          :model="dialogForm"
          :rules="rules"
          :label-width="formLabelWidth"
        >
          <el-form-item prop="name" label="Name">
            <el-input
              v-model="dialogForm.name"
              placeholder="Please enter name"
            />
          </el-form-item>
          <template v-if="dialogType === 'add'">
            <el-form-item prop="isLeaf" label="Leaf node">
              <el-radio-group v-model="dialogForm.isLeaf">
                <el-radio :label="1">Yes</el-radio>
                <el-radio :label="0">No</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="dialogForm.isLeaf"
              prop="parentId"
              label="Parent level "
            >
              <el-select
                v-if="dialogForm.isLeaf === 1"
                v-model="dialogForm.parentId"
                placeholder="Please select the parent level"
                :loading="parentLoading"
                @visible-change="getSpecParent"
              >
                <el-option
                  v-for="item in parentOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog('ruleForm')">Cancel</el-button>
          <el-button
            v-preventReClick
            type="primary"
            @click="submitData('ruleForm')"
          >Confirm</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  productVariantPage,
  productVariantAdd,
  productVariantRead,
  productVariantEdit,
  productVariantList,
  productVariantDeleteName,
  productVariantDeleteVal
} from '@/api/product';
import { postResult } from '@/utils/dataFormat';
export default {
  data() {
    return {
      storeId: null,
      searchCriteria: {},
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      dialogLoading: false,
      dialogType: 'add',
      dialogForm: {},
      rules: {
        name: [
          {
            validator: this.checkStr,
            required: true,
            trigger: 'blur'
          }
        ],
        isLeaf: [
          {
            required: true,
            message: 'Please select the leaf node',
            trigger: 'change'
          }
        ],
        parentId: [
          {
            required: true,
            message: 'Please select the parent node',
            trigger: 'change'
          }
        ]
      },
      formLabelWidth: '110px',
      parentLoading: false,
      parentOptions: [],
      storeMap: {
        1: 'shopify',
        2: 'wooc'
      }
    };
  },
  computed: {
    dialogTitle: function() {
      return this.dialogType === 'add'
        ? 'Add'
        : this.dialogType === 'edit'
          ? 'Edit'
          : '';
    },
    sidebar() {
      return this.$store.state.app.sidebar.opened;
    }
  },
  mounted() {
    this.storeId = Number(this.$route.params.storeId);
    this.init();
  },
  methods: {
    init() {
      this.loading = true;
      productVariantPage({
        name: this.searchCriteria.name ? this.searchCriteria.name : '',
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        storeId: this.storeId
      }).then(res => {
        const arr = [];
        res.data.data.forEach(item => {
          const obj = {};
          Object.assign(obj, item.name);
          obj.listLeaf = item.values;
          arr.push(obj);
        });
        this.tableData = arr;
        this.total = res.data.totalCount;
        this.loading = false;
      });
    },
    searchData() {
      this.currentPage = 1;
      this.init();
    },
    getSpecParent(val) {
      if (!val) {
        return;
      }
      this.parentOptions = [];
      this.parentLoading = true;
      productVariantList({ storeId: this.storeId }).then(res => {
        this.parentLoading = false;
        const arr = [];
        res.data.forEach(item => {
          arr.push(item.name);
        });
        this.parentOptions = arr;
      });
    },
    toggleRow(row) {
      this.$refs.specTable.toggleRowExpansion(row);
    },
    showDialog(type, row) {
      this.dialogType = type;
      this.dialogFormVisible = true;
      this.dialogLoading = false;
      if (type === 'add') {
        // 新增
        this.dialogForm = {};
      } else if (type === 'edit') {
        this.dialogLoading = true;
        productVariantRead(row.id).then(res => {
          this.dialogLoading = false;
          this.dialogForm = res.data;
        });
      }
    },
    submitData(ruleForm) {
      this.$refs[ruleForm].validate(async valid => {
        if (valid) {
          this.dialogForm['storeId'] = this.storeId;
          if (this.dialogType === 'add') {
            if (this.dialogForm.isLeaf === 0) {
              // 控制异常添加或编辑
              this.dialogForm.parentId = 0;
            }
            productVariantAdd(this.dialogForm).then(res => {
              this.dialogFormVisible = false;
              postResult(res, this.$message, this.init);
            });
          } else if (this.dialogType === 'edit') {
            delete this.dialogForm.createTime;
            delete this.dialogForm.updateTime;
            this.dialogForm.listLeaf = [];
            productVariantEdit(this.dialogForm).then(res => {
              this.dialogFormVisible = false;
              postResult(res, this.$message, this.init);
            });
          }
        } else {
          return false;
        }
      });
    },
    deleteItem(row) {
      this.$confirm(
        'This operation will permanently delete the specification. Do you want to continue?',
        'Hint',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          const ids = [];
          ids.push(row.id);
          if (row.isLeaf === 0) {
            // 规格名
            productVariantDeleteName(ids).then(res => {
              postResult(res, this.$message, this.init);
            });
          } else if (row.isLeaf === 1) {
            // 规格值
            productVariantDeleteVal(ids).then(res => {
              postResult(res, this.$message, this.init);
            });
          }
        })
        .catch(() => {
          this.$message.info('undeleted');
        });
    },
    closeDialog(ruleForm) {
      this.dialogFormVisible = false;
      this.$refs[ruleForm].resetFields();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    }
  }
};
</script>
<style lang="scss" scoped></style>
